<template>
  <div class="posts-management-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span class="title">社区帖子管理</span>
          <div class="header-actions">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索帖子"
              class="search-input"
              clearable
              @keyup.enter="handleSearch"
            >
              <template #append>
                <el-button @click="handleSearch">
                  <el-icon><Search /></el-icon>
                </el-button>
              </template>
            </el-input>
            <el-select v-model="postType" placeholder="帖子类型" clearable @change="handleFilterChange">
              <el-option label="全部" value="" />
              <el-option label="综合" value="general" />
              <el-option label="技术" value="technical" />
              <el-option label="问答" value="question" />
              <el-option label="分享" value="share" />
            </el-select>
            <el-select v-model="sortType" placeholder="排序方式" @change="handleFilterChange">
              <el-option label="最新" value="latest" />
              <el-option label="最热" value="hot" />
            </el-select>
            <el-button type="primary" @click="fetchPosts">刷新数据</el-button>
          </div>
        </div>
      </template>
      
      <!-- 帖子列表 -->
      <el-table
        v-loading="loading"
        :data="posts"
        style="width: 100%"
        border
        row-key="id"
        @expand-change="handleExpandChange"
      >
        <el-table-column type="expand">
          <template #default="props">
            <div class="comments-container">
              <div class="comments-header">
                <h3>评论列表</h3>
                <el-pagination
                  :current-page="getCommentCurrentPage(props.row.id)"
                  :page-size="commentPageSize"
                  layout="prev, pager, next"
                  :total="getCommentTotal(props.row.id)"
                  @current-change="(page) => handleCommentPageChange(page, props.row.id)"
                  small
                />
              </div>
              <div v-loading="commentLoading[props.row.id]">
                <el-table
                  :data="comments[props.row.id] || []"
                  style="width: 100%"
                  border
                >
                  <el-table-column prop="id" label="ID" width="80" />
                  <el-table-column prop="content" label="评论内容" min-width="300" show-overflow-tooltip />
                  <el-table-column label="评论者" width="120">
                    <template #default="scope">
                      {{ scope.row.userNickname || '未知用户' }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="createdAt" label="评论时间" width="180">
                    <template #default="scope">
                      {{ formatDate(scope.row.createdAt) }}
                    </template>
                  </el-table-column>
                  <el-table-column label="附件" width="100">
                    <template #default="scope">
                      <el-button 
                        v-if="scope.row.images && scope.row.images.length > 0" 
                        type="primary" 
                        link 
                        @click="viewAttachments(scope.row.images)"
                      >
                        查看图片
                      </el-button>
                      <span v-else>无图片</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="180">
                    <template #default="scope">
                      <el-button type="info" size="small" @click="viewCommentDetail(scope.row)">详情</el-button>
                      <el-button type="danger" size="small" @click="deleteComment(scope.row.id, props.row.id)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <div v-if="comments[props.row.id]?.length === 0" class="no-data">
                  暂无评论
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="title" label="标题" min-width="180" show-overflow-tooltip />
        <el-table-column prop="content" label="内容" min-width="250" show-overflow-tooltip>
          <template #default="scope">
            <div v-html="formatContent(scope.row.content)"></div>
          </template>
        </el-table-column>
        <el-table-column label="发布者" width="120">
          <template #default="scope">
            {{ scope.row.userNickname || (scope.row.user ? scope.row.user.nickname : '未知用户') }}
          </template>
        </el-table-column>
        <el-table-column label="分类" width="100">
          <template #default="scope">
            {{ getPostTypeText(scope.row.type) }}
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="发布时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="统计" width="180">
          <template #default="scope">
            <div class="post-stats">
              <el-tooltip content="浏览量" placement="top">
                <span><el-icon><View /></el-icon> {{ scope.row.viewCount || 0 }}</span>
              </el-tooltip>
              <el-tooltip content="点赞数" placement="top">
                <span><el-icon><Star /></el-icon> {{ scope.row.likeCount || 0 }}</span>
              </el-tooltip>
              <el-tooltip content="评论数" placement="top">
                <span><el-icon><ChatDotRound /></el-icon> {{ scope.row.commentCount || 0 }}</span>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="附件" width="100">
          <template #default="scope">
            <el-button 
              v-if="scope.row.images && scope.row.images.length > 0" 
              type="primary" 
              link 
              @click="viewAttachments(scope.row.images)"
            >
              查看图片
            </el-button>
            <span v-else>无图片</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button type="info" size="small" @click="viewPostDetail(scope.row)">详情</el-button>
            <el-popconfirm
              title="确定要删除这篇帖子吗？此操作不可恢复！"
              @confirm="deletePost(scope.row.id)"
            >
              <template #reference>
                <el-button type="danger" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 附件查看对话框 -->
    <el-dialog
      v-model="attachmentsDialogVisible"
      title="帖子附件"
      width="60%"
    >
      <div class="attachments-container">
        <div v-for="(attachment, index) in currentAttachments" :key="index" class="attachment-item">
          <div v-if="isImage(attachment)">
            <img :src="attachment" class="attachment-image" />
          </div>
          <div v-else class="file-attachment">
            <el-icon><Document /></el-icon>
            <a :href="attachment" target="_blank">{{ `附件${index + 1}` }}</a>
          </div>
        </div>
      </div>
    </el-dialog>
    
    <!-- 帖子详情对话框 -->
    <el-dialog
      v-model="postDetailDialogVisible"
      title="帖子详情"
      width="70%"
    >
      <div v-if="currentPostDetail" class="post-detail">
        <h2 class="post-title">{{ currentPostDetail.title }}</h2>
        <div class="post-meta">
          <span>作者: {{ currentPostDetail.userNickname || (currentPostDetail.user ? currentPostDetail.user.nickname : '未知用户') }}</span>
          <span>分类: {{ getPostTypeText(currentPostDetail.type) }}</span>
          <span>发布时间: {{ formatDate(currentPostDetail.createdAt) }}</span>
          <span>状态: {{ getStatusText(currentPostDetail.status) }}</span>
        </div>
        <div class="post-content" v-html="currentPostDetail.content"></div>
        
        <div v-if="currentPostDetail.images && currentPostDetail.images.length > 0" class="post-images">
          <h3>帖子图片</h3>
          <div class="images-container">
            <div v-for="(image, index) in currentPostDetail.images" :key="index" class="image-item">
              <img :src="image" class="detail-image" />
            </div>
          </div>
        </div>
      </div>
      <div v-else class="no-detail">
        无法加载帖子详情
      </div>
    </el-dialog>
    
    <!-- 评论详情对话框 -->
    <el-dialog
      v-model="commentDetailDialogVisible"
      title="评论详情"
      width="60%"
    >
      <div v-if="currentCommentDetail" class="comment-detail">
        <div class="comment-meta">
          <span>评论者: {{ currentCommentDetail.userNickname || '未知用户' }}</span>
          <span>评论时间: {{ formatDate(currentCommentDetail.createdAt) }}</span>
        </div>
        <div class="comment-content">{{ currentCommentDetail.content }}</div>
        
        <div v-if="currentCommentDetail.images && currentCommentDetail.images.length > 0" class="comment-images">
          <h3>评论图片</h3>
          <div class="images-container">
            <div v-for="(image, index) in currentCommentDetail.images" :key="index" class="image-item">
              <img :src="image" class="detail-image" />
            </div>
          </div>
        </div>
      </div>
      <div v-else class="no-detail">
        无法加载评论详情
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Document, Search, View, Star, ChatDotRound } from '@element-plus/icons-vue'
import axios from 'axios'

// 数据状态
const loading = ref(false)
const posts = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const searchKeyword = ref('')
const postType = ref('')
const sortType = ref('latest')

// 评论相关
const comments = reactive({})
const commentLoading = reactive({})
const commentPagination = reactive({})
const commentPageSize = 10

// 附件查看相关
const attachmentsDialogVisible = ref(false)
const currentAttachments = ref([])

// 帖子详情相关
const postDetailDialogVisible = ref(false)
const currentPostDetail = ref(null)

// 评论详情相关
const commentDetailDialogVisible = ref(false)
const currentCommentDetail = ref(null)

// 查看评论详情
const viewCommentDetail = (comment) => {
  currentCommentDetail.value = comment
  commentDetailDialogVisible.value = true
}

// 获取帖子列表
const fetchPosts = async () => {
  loading.value = true
  try {
    const response = await axios.get('http://localhost:3000/api/forum/posts', {
      params: {
        page: currentPage.value,
        pageSize: pageSize.value,
        keyword: searchKeyword.value,
        type: postType.value || undefined,
        sort: sortType.value === 'hot' ? 'hot' : undefined
      },
      headers: {
        Authorization: `Bearer ${localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')).token : ''}`
      }
    })
    
    if (response.data.posts && Array.isArray(response.data.posts)) {
      posts.value = response.data.posts
      total.value = response.data.total || response.data.posts.length
    } else if (Array.isArray(response.data)) {
      posts.value = response.data
      total.value = response.data.length
    } else {
      posts.value = []
      total.value = 0
    }
  } catch (error) {
    ElMessage.error(`获取帖子列表失败: ${error.message || '未知错误'}`)
  } finally {
    loading.value = false
  }
}

// 获取帖子评论
const fetchPostComments = async (postId, page = 1) => {
  if (!commentLoading[postId]) {
    commentLoading[postId] = false
  }
  
  commentLoading[postId] = true
  try {
    const response = await axios.get(`http://localhost:3000/api/forum/posts/${postId}/comments`, {
      params: {
        page,
        pageSize: commentPageSize
      },
      headers: {
        Authorization: `Bearer ${localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')).token : ''}`
      }
    })
    
    if (response.data.comments && Array.isArray(response.data.comments)) {
      comments[postId] = response.data.comments
      commentPagination[postId] = {
        page,
        total: response.data.total || response.data.comments.length
      }
    } else if (Array.isArray(response.data)) {
      comments[postId] = response.data
      commentPagination[postId] = {
        page,
        total: response.data.length
      }
    } else {
      comments[postId] = []
      commentPagination[postId] = {
        page,
        total: 0
      }
    }
  } catch (error) {
    ElMessage.error(`获取评论失败: ${error.message || '未知错误'}`)
  } finally {
    commentLoading[postId] = false
  }
}

// 删除帖子
const deletePost = async (postId) => {
  try {
    await axios.post(`http://localhost:3000/api/forum/admin/posts/${postId}/delete`, {}, {
      headers: {
        Authorization: `Bearer ${localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')).token : ''}`
      }
    })
    
    ElMessage.success('帖子已成功删除')
    fetchPosts() // 刷新列表
  } catch (error) {
    ElMessage.error(`删除帖子失败: ${error.message || '未知错误'}`)
  }
}

// 删除评论
const deleteComment = async (commentId, postId) => {
  try {
    await axios.post(`http://localhost:3000/api/forum/admin/comments/${commentId}/delete`, {}, {
      headers: {
        Authorization: `Bearer ${localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')).token : ''}`
      }
    })
    
    ElMessage.success('评论已成功删除')
    // 重新获取该帖子的评论
    fetchPostComments(postId, commentPagination[postId]?.page || 1)
    // 刷新帖子列表以更新评论数
    fetchPosts()
  } catch (error) {
    ElMessage.error(`删除评论失败: ${error.message || '未知错误'}`)
  }
}

// 处理展开行变化
const handleExpandChange = (row, expandedRows) => {
  if (expandedRows.length > 0) {
    // 如果是展开，则获取评论
    fetchPostComments(row.id)
  }
}

// 处理评论分页变化
const handleCommentPageChange = (page, postId) => {
  fetchPostComments(postId, page)
}

// 查看帖子详情
const viewPostDetail = (post) => {
  currentPostDetail.value = post
  postDetailDialogVisible.value = true
}

// 查看附件
const viewAttachments = (images) => {
  currentAttachments.value = images
  attachmentsDialogVisible.value = true
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchPosts()
}

// 筛选变化处理
const handleFilterChange = () => {
  currentPage.value = 1
  fetchPosts()
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  fetchPosts()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchPosts()
}

// 获取帖子类型文本
const getPostTypeText = (type) => {
  const typeMap = {
    general: '综合',
    technical: '技术',
    question: '问答',
    share: '分享'
  }
  return typeMap[type] || type
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    pending: '待审核',
    approved: '已通过',
    rejected: '已拒绝'
  }
  return statusMap[status] || status
}

// 获取状态标签类型
const getStatusType = (status) => {
  const typeMap = {
    pending: 'warning',
    approved: 'success',
    rejected: 'danger'
  }
  return typeMap[status] || 'info'
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 格式化内容（截取前100个字符）
const formatContent = (content) => {
  if (!content) return ''
  const plainText = content.replace(/<[^>]+>/g, '')
  return plainText.length > 100 ? plainText.substring(0, 100) + '...' : plainText
}

// 判断是否为图片
const isImage = (url) => {
  if (!url) return false
  return /\.(jpg|jpeg|png|gif|webp)$/i.test(url)
}

// 页面加载时获取数据
onMounted(() => {
  fetchPosts()
})

// 获取评论当前页码
const getCommentCurrentPage = (postId) => {
  return commentPagination[postId]?.page || 1
}

// 获取评论总数
const getCommentTotal = (postId) => {
  return commentPagination[postId]?.total || 0
}
</script>

<style scoped>
.posts-management-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 120px);
}

.box-card {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  border-radius: 8px;
  transition: all 0.3s;
}

.box-card:hover {
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
  flex-wrap: wrap;
}

.search-input {
  width: 250px;
  transition: all 0.3s;
}

.search-input:focus-within {
  width: 280px;
}

.title {
  font-size: 20px;
  font-weight: bold;
  color: #303133;
  position: relative;
  padding-left: 12px;
}

.title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 18px;
  background-color: #409eff;
  border-radius: 2px;
}

.pagination-container {
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
  padding: 10px 0;
}

.post-stats {
  display: flex;
  gap: 12px;
}

.post-stats span {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #606266;
  font-size: 13px;
}

/* 评论容器样式 */
.comments-container {
  padding: 20px;
  background-color: #f9fafc;
  border-radius: 6px;
  margin: 10px;
  border: 1px solid #ebeef5;
}

.comments-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 18px;
  padding-bottom: 12px;
  border-bottom: 1px dashed #e4e7ed;
}

.comments-header h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
  font-weight: 600;
  display: flex;
  align-items: center;
}

.comments-header h3::before {
  content: '';
  display: inline-block;
  width: 3px;
  height: 14px;
  background-color: #409eff;
  margin-right: 8px;
  border-radius: 2px;
}

.no-data {
  text-align: center;
  padding: 30px;
  color: #909399;
  font-size: 14px;
  background-color: #fafafa;
  border-radius: 4px;
  margin: 10px 0;
}

/* 附件样式 */
.attachments-container {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  padding: 10px 0;
}

.attachment-item {
  width: 200px;
  margin-bottom: 16px;
  transition: all 0.3s;
}

.attachment-item:hover {
  transform: translateY(-3px);
}

.attachment-image {
  max-width: 100%;
  max-height: 200px;
  border-radius: 6px;
  border: 1px solid #ebeef5;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
  object-fit: cover;
}

.attachment-image:hover {
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.1);
}

.file-attachment {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 12px;
  border: 1px solid #ebeef5;
  border-radius: 6px;
  background-color: #fff;
  transition: all 0.3s;
}

.file-attachment:hover {
  background-color: #f5f7fa;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.file-attachment a {
  color: #409eff;
  text-decoration: none;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex: 1;
  transition: all 0.3s;
}

.file-attachment a:hover {
  color: #66b1ff;
}

/* 帖子详情样式 */
.post-detail {
  padding: 16px;
  background-color: #fff;
  border-radius: 6px;
}

.post-title {
  margin-bottom: 16px;
  color: #303133;
  font-size: 22px;
  font-weight: 600;
  line-height: 1.4;
  text-align: center;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.post-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 24px;
  color: #606266;
  font-size: 14px;
  background-color: #f9fafc;
  padding: 12px 16px;
  border-radius: 6px;
}

.post-meta span {
  display: flex;
  align-items: center;
  gap: 6px;
}

.post-content {
  margin-bottom: 24px;
  line-height: 1.8;
  white-space: pre-wrap;
  color: #303133;
  font-size: 15px;
  padding: 10px;
  background-color: #fff;
  border-radius: 6px;
}

.post-images {
  margin-top: 24px;
  background-color: #f9fafc;
  padding: 16px;
  border-radius: 6px;
}

.post-images h3 {
  font-size: 16px;
  color: #303133;
  margin-bottom: 16px;
  font-weight: 600;
  border-left: 3px solid #409eff;
  padding-left: 10px;
}

.images-container {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.image-item {
  width: calc(33.33% - 16px);
  margin-bottom: 16px;
  transition: all 0.3s;
}

.image-item:hover {
  transform: scale(1.02);
}

.detail-image {
  width: 100%;
  border-radius: 6px;
  border: 1px solid #ebeef5;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
  object-fit: cover;
}

.detail-image:hover {
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.1);
}

.no-detail {
  text-align: center;
  padding: 40px;
  color: #909399;
  font-size: 16px;
  background-color: #f9fafc;
  border-radius: 6px;
}

/* 评论详情样式 */
.comment-detail {
  padding: 16px;
  background-color: #fff;
  border-radius: 6px;
}

.comment-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 20px;
  color: #606266;
  font-size: 14px;
  background-color: #f9fafc;
  padding: 12px 16px;
  border-radius: 6px;
}

.comment-content {
  margin-bottom: 24px;
  line-height: 1.8;
  white-space: pre-wrap;
  color: #303133;
  font-size: 15px;
  padding: 16px;
  background-color: #f9fafc;
  border-radius: 6px;
  border-left: 3px solid #409eff;
}

.comment-images {
  margin-top: 24px;
  background-color: #f9fafc;
  padding: 16px;
  border-radius: 6px;
}

.comment-images h3 {
  font-size: 16px;
  color: #303133;
  margin-bottom: 16px;
  font-weight: 600;
  border-left: 3px solid #409eff;
  padding-left: 10px;
}

/* 表格样式增强 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.03);
}

:deep(.el-table th) {
  background-color: #f5f7fa !important;
  color: #303133;
  font-weight: 600;
  padding: 12px 0;
}

:deep(.el-table--border th:first-child) {
  border-left: none;
}

:deep(.el-table--border th:last-child) {
  border-right: none;
}

:deep(.el-table__row) {
  transition: all 0.3s;
}

:deep(.el-table__row:hover) {
  background-color: #f0f5ff !important;
}

:deep(.el-tag) {
  border-radius: 4px;
  padding: 0 8px;
  height: 24px;
  line-height: 24px;
}

/* 响应式调整 */
@media screen and (max-width: 1200px) {
  .header-actions {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .search-input {
    width: 100%;
  }
  
  .image-item {
    width: calc(50% - 16px);
  }
}

@media screen and (max-width: 768px) {
  .post-meta {
    flex-direction: column;
    gap: 10px;
  }
  
  .image-item {
    width: 100%;
  }
}
</style>